<template>
  <div class="point-of-raw">
    <div ref="chart" class="thechart"></div>
  </div>
</template>
<script>
import axios from "axios";
import randomcolor from "randomcolor";
import Color from "color";
import * as jsonBeautify from "json-beautify";
let clipboardjs = require("clipboard");

const libDP = require("../lib/Douglas-Peucker");
import * as echarts from "echarts";
import { round, min, max, flatten, map } from "lodash";
const MAP_IMAGES = {
  Vikendi:
    "http://n1-q.mafengwo.net/s16/M00/1F/16/CoUBUl6J6-WAfTq9ABN1dkMMLI4971.jpg#DihorOtok_Main",
  "Erangel (Remastered)":
    "http://n1-q.mafengwo.net/s16/M00/24/CD/CoUBUl6J8CGAZ8FWACwGssFmNzs911.jpg#Baltic_Main.jpg.jpg",
  Miramar:
    "http://b1-q.mafengwo.net/s16/M00/25/07/CoUBUl6J8DuABPwhAB3VGbsEWx0692.jpg#Desert_Main.jpg.jpg",
  Erangel:
    "http://n1-q.mafengwo.net/s16/M00/25/14/CoUBUl6J8E-AbIDmABcvo6NWiPE512.jpg#Erangel_Main.jpg.jpg",
  Sanhok:
    "https://qimage.owhat.cn/prod/master/image/e998aac9-462c-46ce-9c96-0e9506af0da5#Sanhok_Main_High_Res.jpg"
};
const MAP_LENGTH_CENTIMETERS = {
  Vikendi: 612000,
  "Erangel (Remastered)": 816000,
  Miramar: 816000,
  Erangel: 816000,
  Sanhok: 408000
};
const MAP_NAME = "Sanhok";
const MapGameLength = MAP_LENGTH_CENTIMETERS[MAP_NAME];
const MapSize = 1000;
let _scale = MapSize / MapGameLength;
let the_chart = null;
export default {
  name: "POI-RAW",
  data() {
    return {};
  },
  // components:{},
  async mounted() {
    let vue = this;
    let ele = this.$refs["chart"];
    the_chart = echarts.init(ele, "", {
      renderer: "canvas"
    });
    let grid_sssssize = 500;
    let gridPosition = {
      left: 0,
      // right: 10,
      // bottom: 300,
      top: 0,
      width: grid_sssssize,
      height: grid_sssssize
    };
    let background_series = await this.getBackgroundSeries();
    the_chart.setOption({
      backgroundColor: "transparent" || "white",
      color: ["#c23531", "#91c7ae", "#dd8668"],
      tooltip: {
        trigger: "item"
      },
      dataZoom: [
        { type: "inside", xAxisIndex: [0], filterMode: "none" },
        { type: "inside", yAxisIndex: [0], filterMode: "none" }
      ],
      grid: [
        {
          ...gridPosition,
          show: true,
          backgroundColor: "transparent"
        }
      ],
      xAxis: [
        {
          type: "value",
          max: MapGameLength,
          splitLine: {
            show: false
          },
          axisLine: {},
          gridIndex: 0
        }
      ],
      yAxis: [
        {
          type: "value",
          max: MapGameLength,
          splitLine: {
            show: false
          },
          inverse: true,
          gridIndex: 0
        }
      ],
      series: [background_series]
    });
  },
  computed: {
    dataProm: function() {
      return this.getData();
    },
    poisProm: function() {
      return this.ajaxPoisAll();
    }
  },
  methods: {
    async getBackgroundSeries() {
      let seriesBackground = {
        type: "custom",
        data: [[408000, 0]],
        coordinateSystem: "cartesian2d",
        xAxisIndex: 0,
        yAxisIndex: 0,
        z: -1,
        silent: true,
        renderItem: function(params, api) {
          let x = [408000, 408000];
          // debugger
          let coord1 = api.coord([0, 0]);
          let coord2 = api.coord([408000, 408000]);
          return {
            type: "group",
            children: [
              {
                type: "rect",
                shape: {
                  x: coord1[0],
                  y: coord1[1],
                  width: coord2[0] - coord1[0],
                  height: coord2[1] - coord1[1]
                },
                style: {
                  stroke: "blue",
                  lineWidth: 0.1,
                  fill: "rgba(202,202,235,0)"
                }
              },
              {
                type: "image",
                style: {
                  image: MAP_IMAGES[MAP_NAME],
                  x: coord1[0],
                  y: coord1[1],
                  width: coord2[0] - coord1[0],
                  height: coord2[1] - coord1[1],
                  opacity: 0.8
                  // fill:"blue"
                }
              }
            ]
          };
        },
        itemStyle: {
          opacity: 0
        }
      };
      return seriesBackground;
    },
    getData() {
      let link =
        "https://qimage.owhat.cn/prod/master/image/4a1d1810-aee9-4fb1-bacc-b4a41b7f3ca4";
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    ajaxPoisAll() {
      let link =
        "https://qimage.owhat.cn/prod/master/image/e27ac3b6-1c6f-4228-aae6-640d36f057a2";
      return new Promise(resolve => {
        axios
          .get(link)
          .then(axresp => {
            resolve(axresp.data);
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    async selectedInput(indexes) {
      // console.log(indexes);
      let data = await this.dataProm;
      let poiInitialData = await this.poisProm;
      let backgroudSeries = await this.getBackgroundSeries();

      let selectedItems = data.filter((e, i) => indexes.includes(i));
      // debugger;
      if (the_chart) {
        let shejiPois = {};
        for (let item of selectedItems) {
          for (let poi of item.pois) {
            if (!shejiPois[poi]) {
              shejiPois[poi] = {
                name: poi,
                count: 1
              };
            } else {
              shejiPois[poi]["count"]++;
            }
          }
        }
        let shejiLines = {};
        for (let item of selectedItems) {
          if (item.pois.length >= 2) {
            for (let i = 0; i < item.pois.length - 1; i++) {
              let key = [item.pois[i], item.pois[i + 1]].sort().join("+");
              if (!shejiLines[key]) {
                shejiLines[key] = {
                  start: item.pois[i],
                  end: item.pois[i + 1],
                  count: 1
                };
              } else {
                shejiLines[key]["count"]++;
              }
            }
          }
        }
        let mappedshejiPois = map(shejiPois);
        let MAX_POI_COUNT = max(mappedshejiPois.map(e => e.count));
        // console.log({ MAX_POI_COUNT });
        let poiSeriesesData = mappedshejiPois.map(apoi => {
          let mins = 6,
            maxs = 20;
          let poi = poiInitialData.find(e => e.name === apoi.name);
          let size = (apoi.count / MAX_POI_COUNT) * (maxs - mins) + mins;
          let opacity = (apoi.count / MAX_POI_COUNT) * (1 - 0.3) + 0.3;
          let opt = {
            value: [...poi.center_point, poi.name],
            symbolSize: size,
            opacity: opacity
          };
          if (apoi.count >= MAX_POI_COUNT * 2/3 && !poi.is_city) {
            opt.label = {
              show: true,
              formatter: "{@[2]}",
              backgroundColor: "#F6F8FC",
              borderColor: "#8C8D8E",
              borderWidth: 1,
              padding: 4,
              offset: [0, -10],
              borderRadius: 4
            };
          }
          return opt;
        });
        let poiSeries = {
          type: "scatter",
          data: poiSeriesesData,
          itemStyle: {
            color: "white",
            borderWidth: 0.5,
            borderColor: "blue"
          },
          tooltip: {
            formatter: function(params) {
              return params.data.value[2];
            }
          }
        };
        let mappedShejiLines = map(shejiLines);
        let MAX_LINE_COUNT = max(mappedshejiPois.map(e => e.count));
        let lineData = mappedShejiLines.map(aline => {
          let coords = [aline.start, aline.end].map(
            name => poiInitialData.find(e => e.name === name).center_point
          );
          let mins = 3,
            maxs = 20;
          let width = (aline.count / MAX_LINE_COUNT) * (maxs - mins) + mins;
          let opacity = (aline.count / MAX_LINE_COUNT) * (1 - 0.1) + 0.1;
          return {
            coords: coords,
            lineStyle: {
              color: "red",
              width: width,
              opacity: opacity
            }
          };
        });
        let lineSeries = {
          type: "lines",
          xAxisIndex: 0,
          yAxisIndex: 0,
          coordinateSystem: "cartesian2d",
          polyline: true,
          data: lineData
        };
        let mapped = { map, max, flatten };
        // debugger;
        the_chart.setOption({
          series: [backgroudSeries, poiSeries, lineSeries]
        });
        let xys = flatten(
          selectedItems.map(item => {
            return flatten(item.raw_points.map(p => [p.x, p.y]));
          })
        );

        let minmaxXYs = [min(xys), max(xys)];
        the_chart.dispatchAction({
          type: "dataZoom",
          start: (minmaxXYs[0] / MapGameLength) * 100,
          end: (100 * minmaxXYs[1]) / MapGameLength
        });
      }
    }
  }
};
</script>
<style lang="less" scoped>
.thechart {
  width: 500px;
  height: 500px;
}
</style>